
Berta.SettingsRenderer.addType("gallery", function() {
	
	var allContainer;
	var uploadProgress, defaultProgressText;
	var descriptionContainer;
	var entryId, self, uploadId;
	
	var imagesList;
	
	
	/* --------------------------------------------------------------------------------------------------------- */
	/* ---- LOAD  ---------------------------------------------------------------------------------------------- */
	/* --------------------------------------------------------------------------------------------------------- */

	
	function imagesLoad() {
		Berta.Server.instance().get(Berta.Route.get(
			'get:images',
			null,
			{ 'entry_id' : entryId }
		), function(xhrId, response) {
			imagesList = response.json;
			for(var i = 0; i < imagesList.length; i++) {
				imageAddToList(imagesList[i]);
			}
			enableControls();
		});
	}

	

	/* --------------------------------------------------------------------------------------------------------- */
	/* ---- FUNCTIONS  ----------------------------------------------------------------------------------------- */
	/* --------------------------------------------------------------------------------------------------------- */

	
	function imageAddToList(imObj) {
		var el = $('<div class="x-gallery-setting-image x-gallery-setting-noimage x-gallery-setting-image-' + imObj.id + ' clearfix"></div>')
					.data('image', imObj).click(onImageClick);
		
		var im = $('<div class="x-gallery-setting-image-placeholder"><img src="' + imObj.path + '" /></div>').appendTo(el);
		
		var captionEditable = $('<div class="x-editable"></div>')
			.data('berta', {
				"editor":	"Textline",
				"route": "put:image",
				"route_variables": { "id": imObj.id },
				"variable":	"description",
				"editor_params": {
					"caption":	"Caption"
				}
			})
			.html(imObj.description ? imObj.description : '')
			.appendTo(el);
		$('<a href="#" class="x-gallery-setting-image-delete x-icon x-icon-8"></a>').click(onDeleteClick).appendTo(el);
		
		allContainer.find('.x-gallery-setting-list').append(el);
		
		// Make caption editable
		Berta.EditorManager.instance().registerEditables(captionEditable, Berta.Editor.PANEL_CONTEXT);
	}
	function imageRemoveFromList(id) {
		var el = allContainer.find('.x-gallery-setting-image-' + id);
		if(el.length > 0) {
			el.empty().remove();
		}
	}

	
	function enableControls() {
		allContainer.removeClass('x-disabled');
	}
	function disableControls() {
		allContainer.addClass('x-disabled');
	}
	
	
	
	
	/* --------------------------------------------------------------------------------------------------------- */
	/* ---- DELETE IMAGE  -------------------------------------------------------------------------------------- */
	/* --------------------------------------------------------------------------------------------------------- */
	
	function onDeleteClick(event) {
		var imEl = $(event.target).parents('.x-gallery-setting-image');
		imageDelete(imEl.data('image').id);
		
		return false;
	}
	function imageDelete(id) {
		disableControls();
		Berta.Server.instance().del(Berta.Route.get(
			'del:image', { 'id': id }
		), function() {
			imageRemoveFromList(id);
			enableControls();
		});
	}
	
	
	
	/* --------------------------------------------------------------------------------------------------------- */
	/* ---- ORDERING  ------------------------------------------------------------------------------------------ */
	/* --------------------------------------------------------------------------------------------------------- */
	
	/*function sorting_init() {
		listElement.sortable({
			'update': sorting_onUpdate,
			//'handle': '.files-editor-file-handle',
			'axis': 'y'
		});
	}
	function sorting_onUpdate() {
		
	}*/
	
	
	
	/* --------------------------------------------------------------------------------------------------------- */
	/* ---- DESCRIPTION EDIT  ---------------------------------------------------------------------------------- */
	/* --------------------------------------------------------------------------------------------------------- */
	
	function onImageClick(event) {
		var t = $(event.target).closest('.x-gallery-setting-image');
		
		return false;
	}
	
	
	/* --------------------------------------------------------------------------------------------------------- */
	/* ---- UPLOADING  ----------------------------------------------------------------------------------------- */
	/* --------------------------------------------------------------------------------------------------------- */

	/**
	 * Fired when the user has finished choosing files for uploading
	 * @param event
	 */
	function onImageFileChange(event) {
		disableControls();
		var r = Berta.Route.get(
				'post:images',
				null,
				{
					'entry_id': entryId,
					'path': event.target.files
				}
			);

		uploadId = Berta.Server.instance().upload(
			'post',
			r,
			{ /* options for Berta.Server.Upload */
				callbacks: {
					onStart: onUploadStart,
					onProgress: onUploadProgress,
					onComplete: onUploadComplete,
					onFileStart: onUploadFileStart,
					onFileComplete: onUploadFileComplete,
					onFileErorr: onUploadFileError
				}
			}
		);
	}
	function onUploadStart(totalBytes) {
		defaultProgressText = 'Uploading ' + Math.round(totalBytes / 1024) + 'Kb';

		allContainer.addClass('x-gallery-setting-uploading')
					.find('.x-gallery-setting-progress')
					.children('div').css('width', 0).end()
					.children('span').text(defaultProgressText + ' ...');
	}
	function onUploadProgress(file, fileProgress, overallProgress) {
		//$.log('progress ', Math.round(overallProgress * 100), Math.round(overallProgress * 100));

		allContainer.find('.x-gallery-setting-progress')
					.children('div').animate({ 'width': Math.round(overallProgress * 100) + '%' }, 200).end()
					.children('span').text(defaultProgressText + ' - ' + Math.round(overallProgress * 100) + '% ...');
	}
	function onUploadFileStart(file) {}
	function onUploadFileError(file) {}
	function onUploadFileComplete(file, response) {
		//$.log(file, response);
		
		// Add to the visual list, too
		imageAddToList(response.json.values);
	}
	function onUploadComplete(totalBytes) {
		allContainer.removeClass('x-gallery-setting-uploading')
					.find('.x-gallery-setting-progress')
					.children('span').text(defaultProgressText + ' - complete!');
		
		enableControls();
	}
	
	
	
	
	
	
	
	
	
	
	/* --------------------------------------------------------------------------------------------------------- */
	/* ---- MAIN  ---------------------------------------------------------------------------------------------- */
	/* --------------------------------------------------------------------------------------------------------- */

	
	return function(params, definition, setting) {
		// this refers to Berta.SettingsRenderer instance
		
		self = this;
		allContainer = $('<div class="x-gallery-setting x-disabled">' +
				'<div class="x-gallery-setting-toolbar clearfix">' +
					'<span>Add:</span>' +
					'<label class="x-gallery-setting-add-image x-icon x-icon-1"><input type="file" multiple="multiple" /></label>' +
					//'<label class="x-gallery-setting-add-video"><input type="file" multiple="multiple" /></label>' +
					'<label class="x-gallery-setting-add-embed x-icon x-icon-3"></label>' +
					'<label class="x-gallery-setting-add-audio x-icon x-icon-4"></label>' +
				'</div>' +
				'<div class="x-gallery-setting-progress">' +
					'<div></div><span></span>' +
				'</div>' +
				'<div class="x-gallery-setting-list"></div>' +
			'</div>');

		allContainer.find('.x-gallery-setting-add-image input')
						.change(onImageFileChange);

		/*galleryContainer.find('.x-gallery-setting-add-embed')
						.click(onEmbedClick);*/
		
		entryId = params.additional_params[0];
		
		imagesLoad();
			
		return allContainer;
	}
	
}());